import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, FormInstance, message, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import CreateForm from '@/components/CreateForm';
import services from '@/services/certificates';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { RcFile, UploadChangeParam, UploadFile, UploadProps } from 'antd/es/upload';

const { queryList, addData, modifyData, deleteData } = services.CertificatesController

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (id: number | string | null = null, fields: API.Certificates) => {
  const hide = message.loading('正在操作');
  try {
    id ? await modifyData({ id }, { ...fields }) : await addData({ ...fields });
    hide();
    message.success('操作成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.Certificates[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await deleteData({
      id: selectedRows.find((row) => row.id)?.id || '',
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const CertificatesList = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [winProps, setWindowProps] = useState<any>({ title: '新建', id: null, record: {}, width: 1200 })
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [avatar, setAvatar] = useState('')
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      console.log(info.file.originFileObj, info)
      if (info.file.response) setAvatar(info.file.response)
      getBase64(info.file.originFileObj as RcFile, (url) => {
        console.log(url)
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  const columns: any = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 100,
      valueType: 'radio',
      valueEnum: { '男': '男', '女': '女' },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '身份证号',
      dataIndex: 'idNumber',
      key: 'idNumber',
      width: 180,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '证书编号',
      dataIndex: 'certificateNumber',
      key: 'certificateNumber',
      width: 200,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: 250,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '职务',
      dataIndex: 'position',
      key: 'position',
      width: 150,
      valueType: 'select',
      valueEnum: { '项目经理': '项目经理', '资管员': '资管员', '资料员': '资料员', '专职安全员': '专职安全员' },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '技术职称',
      dataIndex: 'technicalTitle',
      key: 'technicalTitle',
      width: 250,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '有效期至',
      dataIndex: 'validUntil',
      key: 'validUntil',
      valueType: 'date',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '初次发证日期',
      dataIndex: 'initialCertificationDate',
      key: 'initialCertificationDate',
      valueType: 'date',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      render: (text: string | undefined) => <img src={text && (`http://api.ynjov.com:8080/${text}`)} alt="avatar" style={{ width: '50px', height: '50px' }} />,
      renderFormItem: (el: any, { record, recordKey }: any, rcForm: FormInstance) => {
        console.log(record, recordKey, el)
        return <Upload
          name="file"
          accept="image/*"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action="/upload" beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          {(imageUrl) ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_: any, record: { id: any; position: string, avatar: string | null }) => (
        <>
          <a
            onClick={() => {
              setImageUrl(`http://api.ynjov.com:8080/${record?.avatar}`)
              setWindowProps({ ...winProps, title: '编辑', id: record.id, record, width: 1200 })
              handleModalVisible(true)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            return window.open("/ccert.html?id=" + record.id, "_blank");
            if (record.position == '项目经理') return window.open("/bcert.html?id=" + record.id, "_blank");
            window.open("/ccert.html?id=" + record.id, "_blank");
          }}>导出预览</a>
        </>
      ),
    },
  ];
  return (
    <PageContainer
      header={{
        title: 'C类职位证书管理',
      }}
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        scroll={{ x: 'max-content' }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setWindowProps({ ...winProps, title: '新建', id: null, record: { companyName: '云南北极光数码科技有限公司' }, width: 1200 })
              handleModalVisible(true)
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params) => {
          const { data, success } = await queryList({
            ...params,
          });
          const datas = Array.isArray(data) ? data.filter((record: { position: string; }) => record.position != '项目经理') : []
          return {
            data: datas || [],
            success,
          };
        }}
        columns={columns}
        rowSelection={{
          type: 'radio',
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}
      <CreateForm
        onCancel={() => {
          handleModalVisible(false)
        }}
        modalVisible={createModalVisible}
        {...winProps}
      >
        <ProTable<API.Certificates, API.Certificates>
          onSubmit={async (value) => {
            value.avatar = avatar
            const success = await handleAdd(winProps.id, value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          form={{
            initialValues: winProps.record,
            layout: 'inline',
            labelCol: { style: { width: 180, margin: 4 } },
            wrapperCol: { style: { margin: 4, minWidth: 300 }, span: 16 },
            labelAlign: 'left',
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>

  );
}

export default CertificatesList;